package jnpf.util;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import jnpf.annotation.JnpfField;
import jnpf.base.ActionResult;
import jnpf.base.UserInfo;
import jnpf.base.entity.DictionaryDataEntity;
import jnpf.base.entity.ProvinceEntity;
import jnpf.base.entity.VisualdevEntity;
import jnpf.base.model.VisualWebTypeEnum;
import jnpf.base.model.dataInterface.DataInterfaceActionVo;
import jnpf.base.model.filter.RuleInfo;
import jnpf.base.service.*;
import jnpf.database.model.entity.DbLinkEntity;
import jnpf.database.model.superQuery.ConditionJsonModel;
import jnpf.database.model.superQuery.SuperQueryConditionModel;
import jnpf.database.util.DynamicDataSourceUtil;
import jnpf.engine.entity.FlowTaskEntity;
import jnpf.engine.entity.FlowTemplateJsonEntity;
import jnpf.engine.model.flowtemplate.FlowTemplateInfoVO;
import jnpf.engine.model.flowtemplatejson.FlowJsonModel;
import jnpf.engine.service.FlowTaskService;
import jnpf.engine.service.FlowTemplateJsonService;
import jnpf.engine.service.FlowTemplateService;
import jnpf.entity.FlowFormEntity;
import jnpf.exception.DataException;
import jnpf.exception.WorkFlowException;
import jnpf.mapper.FlowFormDataMapper;
import jnpf.model.visualJson.TemplateJsonModel;
import jnpf.model.visualJson.config.RegListModel;
import jnpf.onlinedev.model.OnlineDevData;
import jnpf.onlinedev.model.OnlineDevEnum.OnlineDataTypeEnum;
import jnpf.onlinedev.model.OnlineImport.OnlineCusCheckModel;
import jnpf.onlinedev.model.VisualdevModelDataInfoVO;
import jnpf.onlinedev.service.VisualDevInfoService;
import jnpf.onlinedev.service.VisualdevModelDataService;
import jnpf.onlinedev.util.onlineDevUtil.OnlinePublicUtils;
import jnpf.onlinedev.util.onlineDevUtil.OnlineSwapDataUtils;
import jnpf.permission.constant.PermissionConst;
import jnpf.permission.entity.*;
import jnpf.permission.service.*;
import jnpf.service.FlowFormService;
import jnpf.util.context.SpringContext;
import jnpf.util.visiual.JnpfKeyConsts;
import lombok.Cleanup;
import org.apache.poi.ss.formula.functions.T;
import org.mybatis.dynamic.sql.SqlBuilder;
import org.mybatis.dynamic.sql.SqlTable;
import org.mybatis.dynamic.sql.render.RenderingStrategies;
import org.mybatis.dynamic.sql.select.render.SelectStatementProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.sql.Connection;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 数据转换(代码生成器用)
 *
 * @author JNPF开发平台组
 * @version V3.1.0
 * @copyright 引迈信息技术有限公司（https://www.jnpfsoft.com）
 * @date 2021/3/16
 */
@Component
public class GeneraterSwapUtil {

    @Autowired
    private OrganizeService organizeService;

    @Autowired
    private FilterService filterService;

    @Autowired
    private PositionService positionService;

    @Autowired
    private UserService userService;

    @Autowired
    private VisualdevService visualdevService;

    @Autowired
    private VisualDevInfoService visualDevInfoService;

    @Autowired
    private DataInterfaceService dataInterfaceService;

    @Autowired
    private VisualdevModelDataService visualdevModelDataService;

    @Autowired
    private ProvinceService provinceService;

    @Autowired
    private DictionaryDataService dictionaryDataService;

    @Autowired
    private BillRuleService billRuleService;

    @Autowired
    private FlowTaskService flowTaskService;

    @Autowired
    private GroupService groupService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private UserProvider userProvider;

    @Autowired
    private DbLinkService dbLinkService;

    @Autowired
    private FlowTemplateJsonService flowTemplateJsonService;

    @Autowired
    private UserRelationService userRelationService;

    @Autowired
    private FlowFormDataMapper flowFormDataMapper;

    @Autowired
    private OnlineSwapDataUtils swapDataUtils;

    @Autowired
    private FlowFormDataUtil flowFormDataUtil;

    @Autowired
    private DbLinkService dblinkService;

    public final String regEx = "[\\[\\]\"]";
    @Autowired
    private FlowTemplateService flowTemplateService;
    @Autowired
    private FlowFormService flowFormService;

    /**
     * 日期时间戳字符串转换
     *
     * @param date
     * @param format
     * @return
     */
    public String dateSwap(String date, String format) {
        if (StringUtil.isNotEmpty(date)) {
            DateTimeFormatter ftf = DateTimeFormatter.ofPattern(format);
            if (date.contains(",")) {
                String[] dates = date.split(",");
                long time1 = Long.parseLong(dates[0]);
                long time2 = Long.parseLong(dates[1]);
                String value1 = ftf.format(LocalDateTime.ofInstant(Instant.ofEpochMilli(time1), ZoneId.systemDefault()));
                String value2 = ftf.format(LocalDateTime.ofInstant(Instant.ofEpochMilli(time2), ZoneId.systemDefault()));
                return value1 + "至" + value2;
            }
            long time = Long.parseLong(date);
            String value = ftf.format(LocalDateTime.ofInstant(Instant.ofEpochMilli(time), ZoneId.systemDefault()));
            return value;
        }
        return date;
    }

    /**
     * 行政区划转换
     *
     * @param data
     * @return
     */
    public String provinceData(String data) {
        if (StringUtil.isNotEmpty(data)) {
            try {
                if (data.contains("[[")) {
                    List<String> addList = new ArrayList<>();
                    String[][] provinceDataS = JsonUtil.getJsonToBean(data, String[][].class);
                    for (String[] AddressData : provinceDataS) {
                        List<String> provList = new ArrayList(Arrays.asList(AddressData));
                        List<ProvinceEntity> proList = provinceService.getProList(provList);
                        //单条
                        List<String> adList = proList.stream().map(pro -> pro.getFullName()).collect(Collectors.toList());
                        addList.add(String.join("/", adList));
                    }
                    return String.join(";", addList);
                } else if (data.contains("[")) {
                    List<String> idList = JsonUtil.getJsonToList(data, String.class);
                    List<String> nameList = new ArrayList<>();
                    List<ProvinceEntity> proList = provinceService.getProList(idList);
                    for (ProvinceEntity info : proList) {
                        nameList.add(info.getFullName());
                    }
                    return String.join("/", nameList);
                } else {
                    String[] strs = data.split(",");
                    List<String> provList = new ArrayList(Arrays.asList(strs));
                    List<String> proNameList = new ArrayList<>();
                    List<ProvinceEntity> proList = provinceService.getProList(provList);
                    for (ProvinceEntity entity : proList) {
                        proNameList.add(entity.getFullName());
                    }
                    return String.join("/", proNameList);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return "";
    }

    /**
     * 公司部门id转名称
     *
     * @param value
     * @return
     */
    public String comSelectValue(String value, String showLevel) {
        if (StringUtil.isNotEmpty(String.valueOf(value))) {
            OrganizeEntity organizeEntity = organizeService.getInfo(String.valueOf(value));
            if ("all".equals(showLevel)) {
                List<OrganizeEntity> organizeListAll = organizeService.getList();
                String[] organizeTreeId = StringUtil.isNotEmpty(organizeEntity.getOrganizeIdTree()) ? organizeEntity.getOrganizeIdTree().split(",") : new String[]{};
                List<String> organizeTreeList = Arrays.asList(organizeTreeId).stream().filter(t -> !t.isEmpty()).collect(Collectors.toList());
                StringJoiner joiner = new StringJoiner("/");
                for (int i = 0; i < organizeTreeList.size(); i++) {
                    String id = organizeTreeList.get(i);
                    OrganizeEntity entity = organizeListAll.stream().filter(t -> t.getId().equals(id)).findFirst().orElse(null);
                    if (entity != null) {
                        joiner.add(entity.getFullName());
                    }
                }
                value = joiner.toString();
            } else {
                if (organizeEntity != null) {
                    if (organizeEntity.getCategory().equals("company")) {
                        return " ";
                    }
                    value = organizeEntity.getFullName();
                }
            }
        } else {
            value = " ";
        }
        return value;
    }

    /**
     * 公司部门id转名称(多选)
     *
     * @param ids
     * @return
     */
    public String comSelectValues(String ids, Boolean mul) {
        List<String> comValueList = new ArrayList<>();
        if (StringUtil.isEmpty(ids)) {
            return null;
        }
        String Separator = mul ? "," : "/";
        if (ids.contains("[[")) {
            String[][] idArrays = JsonUtil.getJsonToBean(ids, String[][].class);
            for (String[] array : idArrays) {
                List<String> idList = new ArrayList<>();
                for (String s : array) {
                    OrganizeEntity info = organizeService.getInfo(s);
                    idList.add(Objects.nonNull(info) ? info.getFullName() : s);
                }
                String orgCom = idList.stream().collect(Collectors.joining("/"));
                comValueList.add(orgCom);
            }
            return comValueList.stream().collect(Collectors.joining(";"));
        } else if (ids.contains("[")) {
            List<String> idList = JsonUtil.getJsonToList(ids, String.class);
            List<String> nameList = new ArrayList<>();
            for (String orgId : idList) {
                OrganizeEntity info = organizeService.getInfo(orgId);
                nameList.add(Objects.nonNull(info) ? info.getFullName() : orgId);
            }
            return nameList.stream().collect(Collectors.joining(Separator));
        } else {
            ids = ids.replaceAll("\"", "");
            String[] idList = ids.split(",");
            if (idList.length > 0) {
                List<String> comSelectList = new ArrayList<>();
                for (String id : idList) {
                    OrganizeEntity organizeEntity = organizeService.getInfo(id);
                    if (organizeEntity != null) {
                        comSelectList.add(organizeEntity.getFullName());
                    }
                }
                return String.join(",", comSelectList);
            }
        }
        return null;
    }


    /**
     * 岗位id转名称
     *
     * @param id
     * @return
     */
    public String posSelectValue(String id) {
        if (StringUtil.isNotEmpty(id)) {
            PositionEntity positionApiInfo = positionService.getInfo(id);
            if (ObjectUtil.isNotEmpty(positionApiInfo)) {
                return positionApiInfo.getFullName();
            }
            return id;
        }
        return " ";
    }

    /**
     * 岗位id转名称(多选)
     *
     * @param ids
     * @return
     */
    public String posSelectValues(String ids) {
        if (StringUtil.isEmpty(ids)) {
            return "";
        }
        List<String> posList = new ArrayList<>();
        if (ids.contains("[")) {
            List<String> idList = JsonUtil.getJsonToList(ids, String.class);
            List<String> nameList = new ArrayList<>();
            for (String orgId : idList) {
                PositionEntity info = positionService.getInfo(orgId);
                nameList.add(Objects.nonNull(info) ? info.getFullName() : orgId);
            }
            posList = nameList;
        } else {
            String[] idList = ids.split(",");
            if (idList.length > 0) {
                for (String id : idList) {
                    PositionEntity positionEntity = positionService.getInfo(id);
                    if (ObjectUtil.isNotEmpty(positionEntity)) {
                        posList.add(positionEntity.getFullName());
                    }
                }
            }
        }
        return String.join(",", posList);
    }

    /**
     * 用户id转名称
     *
     * @param id
     * @return
     */
    public String userSelectValue(String id) {
        if (StringUtil.isNotEmpty(id)) {
            UserEntity userEntity = userService.getInfo(id);
            if (ObjectUtil.isNotEmpty(userEntity)) {
                return userEntity.getRealName() + "/" + userEntity.getAccount();
            }
            return id;
        }
        return "";
    }

    /**
     * 用户id转名称(多选)
     *
     * @param ids
     * @return
     */
    public String userSelectValues(String ids) {
        if (StringUtil.isEmpty(ids)) {
            return ids;
        }
        if (ids.contains("[")) {
            List<String> nameList = new ArrayList<>();
            List<String> jsonToList = JsonUtil.getJsonToList(ids, String.class);
            for (String userId : jsonToList) {
                UserEntity info = userService.getInfo(userId);
                nameList.add(Objects.nonNull(info) ? info.getRealName() + "/" + info.getAccount() : userId);
            }
            return String.join(";", nameList);
        } else {
            List<String> userInfoList = new ArrayList<>();
            String[] idList = ids.split(",");
            if (idList.length > 0) {
                for (String id : idList) {
                    UserEntity userEntity = userService.getInfo(id);
                    if (ObjectUtil.isNotEmpty(userEntity)) {
                        String info = userEntity.getRealName() + "/" + userEntity.getAccount();
                        userInfoList.add(info);
                    }
                }
            }
            return String.join("-", userInfoList);
        }
    }

    /**
     * 用户组件id转名称(多选)
     *
     * @param ids
     * @return
     */
    public String usersSelectValues(String ids) {
        if (StringUtil.isEmpty(ids)) {
            return ids;
        }
        List<String> dataNoSwapInMethod = OnlinePublicUtils.getDataNoSwapInMethod(ids);
        StringJoiner valueJoin = new StringJoiner(",");
        for (String data : dataNoSwapInMethod) {
            String id = data.contains("--") ? data.substring(0, data.lastIndexOf("--")) : data;
            String type = data.contains("--") ? data.substring(data.lastIndexOf("--") + 2) : "";
            switch (type) {
                case "role":
                    RoleEntity roleEntity = roleService.getInfo(id);
                    if (roleEntity != null) {
                        valueJoin.add(roleEntity.getFullName());
                    } else {
                        valueJoin.add(data);
                    }
                    break;
                case "position":
                    PositionEntity positionEntity = positionService.getInfo(id);
                    if (positionEntity != null) {
                        valueJoin.add(positionEntity.getFullName());
                    } else {
                        valueJoin.add(data);
                    }
                    break;
                case "company":
                case "department":
                    OrganizeEntity organizeEntity = organizeService.getInfo(id);
                    if (organizeEntity != null) {
                        valueJoin.add(organizeEntity.getFullName());
                    } else {
                        valueJoin.add(data);
                    }
                    break;
                case "group":
                    GroupEntity groupEntity = groupService.getInfo(id);
                    if (groupEntity != null) {
                        valueJoin.add(groupEntity.getFullName());
                    } else {
                        valueJoin.add(data);
                    }
                    break;
                case "user":
                default:
                    UserEntity userEntity = userService.getInfo(id);
                    if (userEntity != null) {
                        valueJoin.add(userEntity.getRealName() + "/" + userEntity.getAccount());
                    } else {
                        valueJoin.add(data);
                    }
                    break;
            }
        }
        return valueJoin.toString();
    }


    /**
     * 开关
     *
     * @param data
     * @return
     */
    public String switchSelectValue(String data, String activeTxt, String inactiveTxt) {
        if (StringUtil.isNotEmpty(data)) {
            if (data.equals("0") || data.equals("false")) {
                return inactiveTxt;
            } else if (data.equals("1") || data.equals("true")) {
                return activeTxt;
            } else {
                return data;
            }
        }
        return null;
    }

    /**
     * 关联表单数据转换
     *
     * @param vmodel
     * @param value
     * @param modelId
     * @return
     */
    public String swapRelationFormValue(String vmodel, String value, String modelId, Map<String, Object> formDataMaps) {
        if (StringUtil.isEmpty(value)) {
            return "";
        }
        try {
            VisualdevModelDataInfoVO infoVO = null;
            VisualdevEntity entity = visualdevService.getInfo(modelId);
            if (!StringUtil.isEmpty(entity.getVisualTables()) && !OnlineDevData.TABLE_CONST.equals(entity.getVisualTables())) {
                infoVO = visualDevInfoService.getDetailsDataInfo(value, entity);
            } else {
                infoVO = visualdevModelDataService.infoDataChange(value, entity);
            }
            if (infoVO != null) {
                Map<String, Object> formDataMap = infoVO.getData() != null ? JsonUtil.stringToMap(infoVO.getData()) : new HashMap<>();
                if (formDataMap.size() > 0) {
                    formDataMaps.putAll(formDataMap);
                    formDataMap = OnlinePublicUtils.mapKeyToLower(formDataMap);
                    value = String.valueOf(formDataMap.get(vmodel.toLowerCase()));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return value;
    }


    /**
     * 弹窗
     *
     * @param interfaceId
     * @param propsValue
     * @param relationField
     * @param dataValue
     * @return
     */
    public String getPopupSelectValue(String interfaceId, String propsValue, String relationField, String dataValue, Map<String, Object> dataMaps, String json, int num, Map<String, Object> dataAll) {
        if (StringUtil.isEmpty(interfaceId)) {
            return null;
        }
        List<TemplateJsonModel> list = JsonUtil.getJsonToList(json, TemplateJsonModel.class);
        Map<String, String> infoMap = new HashMap<>();
        for (TemplateJsonModel templateJsonModel : list) {
            if (StringUtil.isNotEmpty(templateJsonModel.getRelationField())) {
                String[] mastTable = templateJsonModel.getRelationField().split("_jnpf_");
                String[] child = templateJsonModel.getRelationField().split("-");
                if (mastTable.length > 1) {
                    if (dataAll.get(mastTable[0]) instanceof Map) {
                        Map<String, Object> mastTableData = (Map<String, Object>) dataAll.get(mastTable[0]);
                        infoMap.put(templateJsonModel.getField(), String.valueOf(mastTableData.get(mastTable[1])));
                    }
                } else if (child.length > 1) {
                    if (dataAll.get(child[0]) instanceof List) {
                        List<Map<String, Object>> chidList = (List<Map<String, Object>>) dataAll.get(child[0]);
                        for (int i = 0; i < chidList.size(); i++) {
                            Map<String, Object> objectMap = chidList.get(i);
                            if (i == num) {
                                infoMap.put(templateJsonModel.getField(), String.valueOf(objectMap.get(child[1])));
                            }
                        }
                    }
                } else {
                    infoMap.put(templateJsonModel.getField(), String.valueOf(dataAll.get(templateJsonModel.getRelationField())));
                }
            }
        }
        if (StringUtil.isNotEmpty(dataValue)) {
            Map<String, String> dataInterfaceMap = new HashMap<>();
            Object data = dataInterfaceService.infoToId(interfaceId, null, infoMap).getData();
            List<Map<String, Object>> dataInterfaceDataList;
            if (data instanceof ActionResult) {
                ActionResult actionVo = (ActionResult) data;
                dataInterfaceDataList = (List<Map<String, Object>>) actionVo.getData();
            } else {
                dataInterfaceDataList = (List<Map<String, Object>>) data;
            }
            if (dataValue.contains("[")) {
                List<String> valueList = JsonUtil.getJsonToList(dataValue, String.class);
                List<String> swapValue = new ArrayList<>();
                for (String va : valueList) {
                    dataInterfaceDataList.stream().filter(map ->
                            map.get(propsValue).equals(va)
                    ).forEach(
                            modelMap -> swapValue.add(String.valueOf(modelMap.get(relationField)))
                    );
                }
                return swapValue.stream().collect(Collectors.joining(","));
            }
            if (dataInterfaceDataList != null) {
                Map<String, Object> dataMap = dataInterfaceDataList.stream().filter(d -> d.get(propsValue).equals(dataValue)).findFirst().orElse(null);
                if (dataMap != null) {
                    dataMaps.putAll(dataMap);
                    return String.valueOf(dataMap.get(relationField));
                }
            }
            return null;
        } else {
            return null;
        }
    }

    /**
     * 弹窗
     *
     * @param interfaceId
     * @param propsValue
     * @param relationField
     * @param dataValue
     * @return
     */
    public String getPopupSelectValue(String interfaceId, String propsValue, String relationField, String dataValue, Map<String, Object> dataMaps) {
        if (StringUtil.isEmpty(interfaceId)) {
            return null;
        }
        if (StringUtil.isNotEmpty(dataValue)) {
            Object data = dataInterfaceService.infoToId(interfaceId, null, null).getData();
            List<Map<String, Object>> dataInterfaceDataList;
            if (data instanceof ActionResult) {
                ActionResult actionVo = (ActionResult) data;
                dataInterfaceDataList = (List<Map<String, Object>>) actionVo.getData();
            } else {
                dataInterfaceDataList = (List<Map<String, Object>>) data;
            }
            if (dataValue.contains("[")) {
                List<String> valueList = JsonUtil.getJsonToList(dataValue, String.class);
                List<String> swapValue = new ArrayList<>();
                for (String va : valueList) {
                    dataInterfaceDataList.stream().filter(map ->
                            map.get(propsValue).equals(va)
                    ).forEach(
                            modelMap -> swapValue.add(String.valueOf(modelMap.get(relationField)))
                    );
                }
                return swapValue.stream().collect(Collectors.joining(","));
            }
            Map<String, Object> dataMap = dataInterfaceDataList.stream().filter(d -> d.get(propsValue).equals(dataValue)).findFirst().orElse(null);
            if (dataMap != null) {
                dataMaps.putAll(dataMap);
                return String.valueOf(dataMap.get(relationField));
            }
            return null;
        } else {
            return null;
        }
    }


    public String getFileNameInJson(String fileJson) {
        if (StringUtil.isNotEmpty(fileJson) && !"null".equals(fileJson)) {
            return fileJson;
        }
        return "";
    }


    /**
     * 获取数据字典数据
     *
     * @param feild
     * @return
     */
    public String getDicName(String feild, String dictionaryTypeId) {
        if (StringUtil.isNotEmpty(feild)) {
            //去除中括号以及双引号
            feild = feild.replaceAll(regEx, "");
            //判断多选框
            String[] feilds = feild.split(",");
            if (feilds.length > 1) {
                StringBuilder feildsValue = new StringBuilder();
                DictionaryDataEntity dictionaryDataEntity;
                for (String feil : feilds) {
                    dictionaryDataEntity = dictionaryDataService.getSwapInfo(feil, dictionaryTypeId);
                    if (dictionaryDataEntity != null) {
                        feildsValue.append(dictionaryDataEntity.getFullName() + ",");
                    } else {
                        feildsValue.append(feil + ",");
                    }
                }
                String finalValue;
                if (StringUtil.isEmpty(feildsValue) || feildsValue.equals("")) {
                    finalValue = feildsValue.toString();
                } else {
                    finalValue = feildsValue.substring(0, feildsValue.length() - 1);
                }
                return finalValue;
            }
            DictionaryDataEntity dictionaryDataentity = dictionaryDataService.getSwapInfo(feild, dictionaryTypeId);
            if (dictionaryDataentity != null) {
                return dictionaryDataentity.getFullName();
            }
            return feild;
        }
        return feild;
    }

    /**
     * 获取远端数据
     *
     * @param urlId
     * @param label
     * @param value
     * @param feildValue
     * @return
     * @throws IOException
     */
    public String getDynName(String urlId, String label, String value, String feildValue, String json, int num, Map<String, Object> dataAll) {
        List<TemplateJsonModel> list = JsonUtil.getJsonToList(json, TemplateJsonModel.class);
        Map<String, String> infoMap = list.size() > 0 ? new HashMap<>() : null;
        for (TemplateJsonModel templateJsonModel : list) {
            if (StringUtil.isNotEmpty(templateJsonModel.getRelationField())) {
                String[] mastTable = templateJsonModel.getRelationField().split("_jnpf_");
                String[] child = templateJsonModel.getRelationField().split("-");
                if (mastTable.length > 1) {
                    if (dataAll.get(mastTable[0]) instanceof Map) {
                        Map<String, Object> mastTableData = (Map<String, Object>) dataAll.get(mastTable[0]);
                        infoMap.put(templateJsonModel.getField(), String.valueOf(mastTableData.get(mastTable[1])));
                    }
                } else if (child.length > 1) {
                    if (dataAll.get(child[0]) instanceof List) {
                        List<Map<String, Object>> chidList = (List<Map<String, Object>>) dataAll.get(child[0]);
                        for (int i = 0; i < chidList.size(); i++) {
                            Map<String, Object> objectMap = chidList.get(i);
                            if (i == num) {
                                infoMap.put(templateJsonModel.getField(), String.valueOf(objectMap.get(child[1])));
                            }
                        }
                    }
                } else {
                    infoMap.put(templateJsonModel.getField(), String.valueOf(dataAll.get(templateJsonModel.getRelationField())));
                }
            }
        }
        if (StringUtil.isNotEmpty(feildValue)) {
            //去除中括号以及双引号
            feildValue = feildValue.replaceAll(regEx, "");
            //获取远端数据
            Map<String, String> a = new HashMap<>();
            ActionResult object = dataInterfaceService.infoToId(urlId, null, infoMap);
            if (object.getData() != null && object.getData() instanceof DataInterfaceActionVo) {
                DataInterfaceActionVo vo = (DataInterfaceActionVo) object.getData();
                List<Map<String, Object>> dataList = (List<Map<String, Object>>) vo.getData();
                //判断是否多选
                String[] feildValues = feildValue.split(",");
                if (feildValues.length > 0) {
                    //转换的真实值
                    StringBuilder feildVa = new StringBuilder();
                    for (String feild : feildValues) {
                        for (Map<String, Object> data : dataList) {
                            if (String.valueOf(data.get(value)).equals(feild)) {
                                feildVa.append(data.get(label) + ",");
                            }
                        }
                    }
                    String finalValue;
                    if (StringUtil.isEmpty(feildVa) || feildVa.equals("")) {
                        finalValue = feildVa.toString();
                    } else {
                        finalValue = feildVa.substring(0, feildVa.length() - 1);
                    }
                    return finalValue;
                }
                for (Map<String, Object> data : dataList) {
                    if (feildValue.equals(String.valueOf(data.get(value)))) {
                        return data.get(label).toString();
                    }
                    return feildValue;
                }
            }
            return feildValue;
        }
        return feildValue;
    }

    /**
     * 获取远端数据
     *
     * @param urlId
     * @param name
     * @param id
     * @param children
     * @param feildValue
     * @return
     */
    public String getDynName(String urlId, String name, String id, String children, String feildValue, boolean mul) {
        List<String> result = new ArrayList<>();
        String sep = ",";
        if (mul) {
            sep = "/";
        }
        if (StringUtil.isNotEmpty(feildValue)) {
            Map<String, String> a = new HashMap<>();
            ActionResult object = dataInterfaceService.infoToId(urlId, null, null);
            List<Map<String, Object>> dataList = (List<Map<String, Object>>) object.getData();
//			if (actionVo.getData() instanceof List) {
//				dataList = (List<Map<String, Object>>) actionVo.getData();
//			}
            JSONArray dataAll = JsonUtil.getListToJsonArray(dataList);
            List<Map<String, Object>> list = new ArrayList<>();
            treeToList(id, name, children, dataAll, list);
            String value = feildValue.replaceAll("\\[", "").replaceAll("\\]", "");
            Map<String, String> resultMap = new HashMap<>();
            list.stream().forEach(t -> {
                resultMap.put(String.valueOf(t.get(id)), String.valueOf(t.get(name)));
            });

            if (feildValue.startsWith("[[")) {
                String[][] fv = JsonUtil.getJsonToBean(feildValue, String[][].class);
                StringJoiner f1 = new StringJoiner(",");
                for (String[] f : fv) {
                    StringJoiner v1 = new StringJoiner("/");
                    for (String v : f) {
                        v1.add(resultMap.get(v));
                    }
                    f1.add(v1.toString());
                }
                return f1.toString();
            } else if (feildValue.startsWith("[")) {
                List<String> fvs = JsonUtil.getJsonToList(feildValue, String.class);
                return fvs.stream().map(m -> resultMap.get(m)).collect(Collectors.joining(sep));
            } else {
                return resultMap.get(feildValue);
            }
        }
        return feildValue;
    }


    /**
     * 获取远端数据
     *
     * @param urlId
     * @param name
     * @param id
     * @param children
     * @param feildValue
     * @param mul        是否多选
     * @param isFullPath 全路径
     * @return
     */
    public String getDynName(String urlId, String name, String id, String children, String feildValue, boolean mul, boolean isFullPath, String json, int num, Map<String, Object> dataAll1) {
        List<TemplateJsonModel> list = JsonUtil.getJsonToList(json, TemplateJsonModel.class);
        Map<String, String> infoMap = list.size() > 0 ? new HashMap<>() : null;
        for (TemplateJsonModel templateJsonModel : list) {
            if (StringUtil.isNotEmpty(templateJsonModel.getRelationField())) {
                String[] mastTable = templateJsonModel.getRelationField().split("_jnpf_");
                String[] child = templateJsonModel.getRelationField().split("-");
                if (mastTable.length > 1) {
                    if (dataAll1.get(mastTable[0]) instanceof Map) {
                        Map<String, Object> mastTableData = (Map<String, Object>) dataAll1.get(mastTable[0]);
                        infoMap.put(templateJsonModel.getField(), String.valueOf(mastTableData.get(mastTable[1])));
                    }
                } else if (child.length > 1) {
                    if (dataAll1.get(child[0]) instanceof List) {
                        List<Map<String, Object>> chidList = (List<Map<String, Object>>) dataAll1.get(child[0]);
                        for (int i = 0; i < chidList.size(); i++) {
                            Map<String, Object> objectMap = chidList.get(i);
                            if (i == num) {
                                infoMap.put(templateJsonModel.getField(), String.valueOf(objectMap.get(child[1])));
                            }
                        }
                    }
                } else {
                    infoMap.put(templateJsonModel.getField(), String.valueOf(dataAll1.get(templateJsonModel.getRelationField())));
                }
            }
        }

        List<String> result = new ArrayList<>();
        String sep = ",";
        if (mul) {
            sep = "/";
        }
        if (StringUtil.isNotEmpty(feildValue)) {
            Map<String, String> a = new HashMap<>();
            ActionResult data = dataInterfaceService.infoToId(urlId, null, infoMap);
            List<Map<String, Object>> dataList = (List<Map<String, Object>>) data.getData();
//			if (actionVo.getData() instanceof List) {
//				dataList = (List<Map<String, Object>>) actionVo.getData();
//			}
            JSONArray dataAll = JsonUtil.getListToJsonArray(dataList);
            List<Map<String, Object>> datalist = new ArrayList<>();
            treeToList(id, name, children, dataAll, datalist);
            String value = feildValue.replaceAll("\\[", "").replaceAll("\\]", "");
            Map<String, String> resultMap = new HashMap<>();
            datalist.stream().forEach(t -> {
                resultMap.put(String.valueOf(t.get(id)), String.valueOf(t.get(name)));
            });

            if (feildValue.startsWith("[[")) {
                String[][] fv = JsonUtil.getJsonToBean(feildValue, String[][].class);
                StringJoiner f1 = new StringJoiner(",");
                for (String[] f : fv) {
                    StringJoiner v1 = new StringJoiner("/");
                    if (isFullPath) {
                        for (String v : f) {
                            v1.add(resultMap.get(v));
                        }
                    } else {
                        v1.add(resultMap.get(f[f.length - 1]));
                    }
                    f1.add(v1.toString());
                }
                return f1.toString();
            } else if (feildValue.startsWith("[")) {
                List<String> fvs = JsonUtil.getJsonToList(feildValue, String.class);
                if (isFullPath) {
                    return fvs.stream().map(m -> resultMap.get(m)).collect(Collectors.joining(sep));
                } else {
                    return fvs.size() > 0 ? Optional.ofNullable(resultMap.get(fvs.get(fvs.size() > 0 ? fvs.size() - 1 : 0))).orElse(null) : null;
                }
            } else {
                return resultMap.get(feildValue);
            }
        }
        return feildValue;
    }

    /**
     * 树转成list
     **/
    private void treeToList(String id, String fullName, String children, JSONArray data, List<Map<String, Object>> result) {
        if (data != null) {
            for (int i = 0; i < data.size(); i++) {
                JSONObject ob = data.getJSONObject(i);
                Map<String, Object> tree = new HashMap<>(16);
                tree.put(id, String.valueOf(ob.get(id)));
                tree.put(fullName, String.valueOf(ob.get(fullName)));
                result.add(tree);
                if (ob.get(children) != null) {
                    JSONArray childArray = ob.getJSONArray(children);
                    treeToList(id, fullName, children, childArray, result);
                }
            }
        }
    }

    /**
     * 生成单据规则
     *
     * @param encode
     * @param isCache
     * @return
     * @throws DataException
     */
    public String getBillNumber(String encode, Boolean isCache) throws DataException {
        return billRuleService.getBillNumber(encode, isCache);
    }

    /**
     * 功能流程 获取可视化实体
     *
     * @param visualId
     * @return
     */
    public VisualdevEntity getVisualEntity(String visualId) {
        VisualdevEntity info = visualdevService.getInfo(visualId);
        if (info != null) {
            return info;
        }
        return new VisualdevEntity();
    }

    public UserEntity getUser(String userId) {
        return userService.getInfo(userId);
    }

    /**
     * 获取流程任务
     *
     * @param id
     * @param columns
     * @return
     */
    public FlowTaskEntity getInfoSubmit(String id, SFunction<FlowTaskEntity, ?>... columns) {
        return flowTaskService.getInfoSubmit(id, columns);
    }

    public void deleteFlowTask(FlowTaskEntity flowTaskEntity) throws WorkFlowException {
        flowTaskService.delete(flowTaskEntity);
    }

    public void hasFlowTemplate(String flowId) throws WorkFlowException {
        boolean hasFlow = StringUtil.isEmpty(flowId);
        if (hasFlow) {
            throw new WorkFlowException("该功能未配置流程不可用");
        }
        FlowTemplateJsonEntity info = flowTemplateJsonService.getInfo(flowId);
    }

    public String getGroupSelect(String groupIds) {
        if (StringUtil.isEmpty(groupIds)) {
            return groupIds;
        }
        List<String> swapList = new ArrayList<>();
        if (groupIds.contains("[")) {
            List<String> groups = JsonUtil.getJsonToList(groupIds, String.class);
            for (String g : groups) {
                GroupEntity info = groupService.getInfo(g);
                String s = info != null ? info.getFullName() : "";
                swapList.add(s);
            }
        } else {
            GroupEntity info = groupService.getInfo(groupIds);
            swapList.add(info != null ? info.getFullName() : "");
        }
        return swapList.stream().collect(Collectors.joining(","));
    }

    public String getRoleSelect(String roleIds) {
        if (StringUtil.isEmpty(roleIds)) {
            return roleIds;
        }
        List<String> swapList = new ArrayList<>();
        if (roleIds.contains("[")) {
            List<String> groups = JsonUtil.getJsonToList(roleIds, String.class);
            for (String g : groups) {
                RoleEntity info = roleService.getInfo(g);
                String s = info != null ? info.getFullName() : "";
                swapList.add(s);
            }
        } else {
            RoleEntity info = roleService.getInfo(roleIds);
            swapList.add(info != null ? info.getFullName() : "");
        }
        return swapList.stream().collect(Collectors.joining(","));
    }


    /**
     * 高级查询
     *
     * @param conditionModel
     * @param entity
     * @param num
     * @return
     */
    public Integer getCondition(SuperQueryConditionModel conditionModel, Object entity, int num) {
        QueryWrapper<?> queryWrapper = conditionModel.getObj();
        List<ConditionJsonModel> queryConditionModels = conditionModel.getConditionList();
        String op = conditionModel.getMatchLogic();
        String tableName = conditionModel.getTableName();
        List<ConditionJsonModel> useCondition = new ArrayList<>();
        for (ConditionJsonModel queryConditionModel : queryConditionModels) {
            if (queryConditionModel.getTableName().equalsIgnoreCase(tableName)) {
                if (queryConditionModel.getField().contains("jnpf")) {
                    String child = queryConditionModel.getField();
                    String s1 = child.substring(child.lastIndexOf("jnpf_")).replace("jnpf_", "");
                    queryConditionModel.setField(s1);
                }
                if (queryConditionModel.getField().startsWith("tableField")) {
                    String child = queryConditionModel.getField();
                    String s1 = child.substring(child.indexOf("-") + 1);
                    queryConditionModel.setField(s1);
                }
                useCondition.add(queryConditionModel);
            }
        }

        if (queryConditionModels.size() < 1 || useCondition.size() < 1) {
            return num;
        }
        if (useCondition.size() > 0) {
            num += 1;
        }
        //处理控件 转换为有效值
        for (ConditionJsonModel queryConditionModel : useCondition) {
            String jnpfKey = queryConditionModel.getJnpfKey();
            String fieldValue = queryConditionModel.getFieldValue();
            if (StringUtil.isEmpty(fieldValue)) {
                if (jnpfKey.equals(JnpfKeyConsts.CASCADER) || jnpfKey.equals(JnpfKeyConsts.CHECKBOX) || jnpfKey.equals(JnpfKeyConsts.COMSELECT) || jnpfKey.equals(JnpfKeyConsts.ADDRESS)) {
                    queryConditionModel.setFieldValue("[]");
                } else {
                    queryConditionModel.setFieldValue("");
                }
                if (queryConditionModel.getSymbol().equals("like")) {
                    queryConditionModel.setSymbol("==");
                } else if (queryConditionModel.getSymbol().equals("notLike")) {
                    queryConditionModel.setSymbol("<>");
                }
            }
            if (jnpfKey.equals(JnpfKeyConsts.DATE)) {
                String startTime = "";
                if (StringUtil.isNotEmpty(fieldValue)) {
                    Long o1 = Long.valueOf(fieldValue);
                    startTime = DateUtil.daFormatHHMMSS(o1);
                }
                queryConditionModel.setFieldValue(startTime);
            } else if (jnpfKey.equals(JnpfKeyConsts.CREATETIME) || jnpfKey.equals(JnpfKeyConsts.MODIFYTIME)) {
                String startTime = "";
                if (StringUtil.isNotEmpty(fieldValue)) {
                    Long o1 = Long.valueOf(fieldValue);
                    startTime = DateUtil.daFormatHHMMSS(o1);
                }
                queryConditionModel.setFieldValue(startTime);
            } else if (jnpfKey.equals(JnpfKeyConsts.CURRORGANIZE)) {
                if (StringUtil.isNotEmpty(fieldValue)) {
                    List<String> orgList = JsonUtil.getJsonToList(fieldValue, String.class);
                    queryConditionModel.setFieldValue(orgList.get(orgList.size() - 1));
                }
            }
        }
        //反射获取数据库实际字段
        Class<?> aClass = entity.getClass();

        queryWrapper.and(tw -> {
            for (ConditionJsonModel conditionJsonModel : useCondition) {
                String conditionField = conditionJsonModel.getField();
                String jnpfKey = conditionJsonModel.getJnpfKey();
                Field declaredField = null;
                try {
                    declaredField = aClass.getDeclaredField(conditionField);
                } catch (NoSuchFieldException e) {
                    e.printStackTrace();
                }
                declaredField.setAccessible(true);
                String field = declaredField.getAnnotation(TableField.class).value();
                String fieldValue = conditionJsonModel.getFieldValue();
                String symbol = conditionJsonModel.getSymbol();
                if ("AND".equalsIgnoreCase(op)) {
                    if (symbol.equals("==")) {
                        tw.and(qw -> {
                                    List<String> multJnpf = new ArrayList() {{
                                        add(JnpfKeyConsts.CASCADER);
                                        add(JnpfKeyConsts.COMSELECT);
                                        add(JnpfKeyConsts.ADDRESS);
                                        add(JnpfKeyConsts.SELECT);
                                        add(JnpfKeyConsts.TREESELECT);
                                    }};
                                    if (JnpfKeyConsts.CHECKBOX.equals(jnpfKey) || (multJnpf.contains(jnpfKey) && conditionJsonModel.isFormMultiple())) {
                                        //todo 多选，高级查询只选一个，需要拼成数组查询，其他控件目前没发现，后续添加至此
                                        String eavalue="";
                                        if(fieldValue.contains("[")){
                                            eavalue="["+fieldValue+"]";
                                        }else {
                                            JSONArray jarr = new JSONArray();
                                            jarr.add(fieldValue);
                                            eavalue=jarr.toJSONString();
                                        }
                                        qw.eq(field, eavalue);
                                    } else if (!jnpfKey.equals(JnpfKeyConsts.NUM_INPUT) && !jnpfKey.equals(JnpfKeyConsts.CALCULATE)) {
                                        qw.eq(field, fieldValue);
                                    } else {
                                        if (StringUtil.isNotEmpty(fieldValue)) {
                                            qw.eq(field, fieldValue);
                                        }
                                    }
                                    if (StringUtil.isEmpty(fieldValue)) {
                                        qw.or(
                                                ew -> ew.isNull(field)
                                        );
                                    }
                                }
                        );
                    } else if (symbol.equals(">=")) {
                        tw.ge(field, fieldValue);
                    } else if (symbol.equals("<=")) {
                        tw.and(ew -> {
                            ew.le(field, fieldValue);
                            ew.and(
                                    qw -> qw.ne(field, "")
                            );
                        });
                    } else if (symbol.equals(">")) {
                        tw.gt(field, fieldValue);
                    } else if (symbol.equals("<")) {
                        tw.and(ew -> {
                            ew.lt(field, fieldValue);
                            ew.and(
                                    qw -> qw.ne(field, "")
                            );
                        });
                    } else if (symbol.equals("<>")) {
                        tw.and(ew -> {
                            ew.ne(field, fieldValue);
                            if (StringUtil.isNotEmpty(fieldValue)) {
                                ew.or(
                                        qw -> qw.isNull(field)
                                );
                            } else {
                                ew.and(
                                        qw -> qw.isNotNull(field)
                                );
                            }
                        });
                    } else if (symbol.equals("like")) {
                        tw.and(ew -> {
                            if (StringUtil.isNotEmpty(fieldValue)) {
                                ew.like(field, fieldValue);
                            } else {
                                ew.isNull(field);
                            }
                        });
                    } else if (symbol.equals("notLike")) {
                        tw.and(ew -> {
                            if (StringUtil.isNotEmpty(fieldValue)) {
                                ew.notLike(field, fieldValue);
                                ew.or(
                                        qw -> qw.isNull(field)
                                );
                            } else {
                                ew.isNotNull(field);
                            }
                        });
                    }
                } else {
                    if (symbol.equals("==")) {
                        tw.or(
                                qw -> qw.eq(field, fieldValue)
                        );
                    } else if (symbol.equals(">=")) {
                        tw.or(
                                qw -> qw.ge(field, fieldValue)
                        );
                    } else if (symbol.equals("<=")) {
                        tw.or(
                                qw -> qw.le(field, fieldValue)
                        );
                    } else if (symbol.equals(">")) {
                        tw.or(
                                qw -> qw.gt(field, fieldValue)
                        );
                    } else if (symbol.equals("<")) {
                        tw.or(
                                qw -> qw.lt(field, fieldValue)
                        );
                    } else if (symbol.equals("<>")) {
                        tw.or(
                                qw -> qw.ne(field, fieldValue)
                        );
                        if (StringUtil.isNotEmpty(fieldValue)) {
                            tw.or(
                                    qw -> qw.isNull(field)
                            );
                        }
                    } else if (symbol.equals("like")) {
                        if (StringUtil.isNotEmpty(fieldValue)) {
                            tw.or(
                                    qw -> qw.like(field, fieldValue)
                            );
                        } else {
                            tw.or(
                                    qw -> qw.isNull(field)
                            );
                        }
                    } else if (symbol.equals("notLike")) {
                        if (StringUtil.isNotEmpty(fieldValue)) {
                            tw.or(
                                    qw -> qw.notLike(field, fieldValue)
                            );
                            tw.or(
                                    qw -> qw.isNull(field)
                            );
                        } else {
                            tw.or(
                                    qw -> qw.isNotNull(field)
                            );
                        }
                    }
                }
            }
        });
        return num;
    }

    public List<String> getIntersection(List<List<String>> lists) {
        if (lists == null || lists.size() == 0) {
            return new ArrayList<>();
        }
        ArrayList<List<String>> arrayList = new ArrayList<>(lists);
        for (int i = 0; i < arrayList.size(); i++) {
            List<String> list = arrayList.get(i);
            if (list == null || list.size() == 0) {
                return new ArrayList<>();
            }
        }
        List<String> intersection = arrayList.get(0);
        for (int i = 0; i < arrayList.size(); i++) {
            List<String> list = arrayList.get(i);
            intersection.retainAll(arrayList.get(i));
        }
        return intersection;
    }

    public Map<String, Object> putCache(Map<String, Object> localCache) {
        //读取系统控件 所需编码 id
        Map<String, Object> depMap = organizeService.getOrgEncodeAndName("department");
        localCache.put("_dep_map", depMap);
        Map<String, Object> comMap = organizeService.getOrgNameAndId("");
        localCache.put("_com_map", comMap);
        Map<String, Object> posMap = positionService.getPosEncodeAndName();
        localCache.put("_pos_map", posMap);
        Map<String, Object> userMap = userService.getUserNameAndIdMap();
        localCache.put("_user_map", userMap);
        Map<String, Object> roleMap = roleService.getRoleNameAndIdMap();
        localCache.put("_role_map", roleMap);
        Map<String, Object> groupMap = groupService.getGroupEncodeMap();
        localCache.put("_group_map", groupMap);
        return localCache;
    }

    public String excelCheckForm(JnpfField jnpfField, String value, Map<String, Object> insMap, String dblink, Map<String, Object> localCache, StringJoiner errInfo) throws Exception {
        UserInfo userInfo = userProvider.get();
        UserEntity userEntity = userService.getInfo(userInfo.getUserId());
        String jnpfKey = jnpfField.jnpfKey();
        String label = jnpfField.label();
        String vModel = jnpfField.vModel();
        boolean multiple = jnpfField.multiple();
        String comInputIDStr = null;

        //读取系统控件 所需编码 id
        Map<String, Object> depMap = (Map<String, Object>) localCache.get("_dep_map");
        Map<String, Object> comMap = (Map<String, Object>) localCache.get("_com_map");
        Map<String, Object> posMap = (Map<String, Object>) localCache.get("_pos_map");
        Map<String, Object> userMap = (Map<String, Object>) localCache.get("_user_map");
        Map<String, Object> roleMap = (Map<String, Object>) localCache.get("_role_map");
        Map<String, Object> groupMap = (Map<String, Object>) localCache.get("_group_map");

        List<String> systemList = new ArrayList<>();
        systemList.add(JnpfKeyConsts.CREATETIME);
        systemList.add(JnpfKeyConsts.BILLRULE);
        systemList.add(JnpfKeyConsts.CREATEUSER);
        systemList.add(JnpfKeyConsts.CURRORGANIZE);
        systemList.add(JnpfKeyConsts.CURRDEPT);
        systemList.add(JnpfKeyConsts.MODIFYTIME);
        systemList.add(JnpfKeyConsts.CURRPOSITION);
        if (!systemList.contains(jnpfKey)) {
            if (value == null || "null".equals(value) || StringUtil.isEmpty(value)) {
                return null;
            }
        }
        if (JnpfKeyConsts.CHECKBOX.equals(jnpfKey)) {
            multiple = true;
        }
        boolean valueMul = value.contains(",");
        value = value.trim();
        List<String> valueList = valueMul ? Arrays.asList(value.split(",")) : new ArrayList<>();
        if (!valueMul) {
            valueList.add(value);
        }
        List<String> ableDepIds = JsonUtil.getJsonToList(jnpfField.ableDepIds(), String.class);
        List<String> ableGroupIds = JsonUtil.getJsonToList(jnpfField.ableGroupIds(), String.class);
        List<String> ablePosIds = JsonUtil.getJsonToList(jnpfField.ablePosIds(), String.class);
        List<String> ableRoleIds = JsonUtil.getJsonToList(jnpfField.ableRoleIds(), String.class);
        List<String> ableUserIds = JsonUtil.getJsonToList(jnpfField.ableUserIds(), String.class);
        List<String> ableIds = JsonUtil.getJsonToList(jnpfField.ableIds(), String.class);

        String dataType = jnpfField.dataType();
        OnlineCusCheckModel cusCheckModel = new OnlineCusCheckModel();
        cusCheckModel.setAbleDepIds(ableDepIds);
        cusCheckModel.setAbleGroupIds(ableGroupIds);
        cusCheckModel.setAblePosIds(ablePosIds);
        cusCheckModel.setAbleRoleIds(ableRoleIds);
        cusCheckModel.setAbleUserIds(ableUserIds);
        cusCheckModel.setControlType(jnpfKey);
        List<String> dataList;
        switch (jnpfKey) {
            /**
             * 高级控件
             */
            case JnpfKeyConsts.COMSELECT:
                boolean comErrorHapen = false;
                if (!multiple) {
                    if (valueList.size() > 1) {
                        comErrorHapen = true;
                        errInfo.add(label + "非多选");
                    }
                }
                if (!comErrorHapen) {
                    boolean comvalueErroHappen = false;
                    List<List<String>> comTwoList = new ArrayList<>();
                    List<String> comOneList = new ArrayList<>();
                    for (String comValue : valueList) {
                        String[] split = comValue.split("/");
                        List<String> comIdList = new ArrayList<>();
                        for (String comId : split) {
                            Object o = comMap.get(comId);
                            if (o != null) {
                                comIdList.add(o.toString());
                            } else {
                                comvalueErroHappen = true;
                                break;
                            }
                        }
                        comOneList.addAll(comIdList);
                        comTwoList.add(comIdList);
                    }
                    if (comvalueErroHappen) {
                        errInfo.add(label + "值不正确");
                    } else {
                        insMap.put(vModel, !multiple ? JsonUtil.getObjectToString(comOneList) : JsonUtil.getObjectToString(comTwoList));
                    }
                }
                break;
            case JnpfKeyConsts.DEPSELECT:
                dataList = checkOptionsControl(multiple, insMap, vModel, label, depMap, valueList, errInfo);
                if (dataList.size() == valueList.size() && jnpfField.selectType().equals("custom")) {
                    cusCheckModel.setDataList(dataList);
                    swapDataUtils.checkCustomControl(cusCheckModel, errInfo, label);
                }
                break;
            case JnpfKeyConsts.POSSELECT:
                dataList = checkOptionsControl(multiple, insMap, vModel, label, posMap, valueList, errInfo);
                if (dataList.size() == valueList.size() && jnpfField.selectType().equals("custom")) {
                    cusCheckModel.setDataList(dataList);
                    swapDataUtils.checkCustomControl(cusCheckModel, errInfo, label);
                }
                break;
            case JnpfKeyConsts.USERSELECT:
                dataList = checkOptionsControl(multiple, insMap, vModel, label, userMap, valueList, errInfo);
                if (dataList.size() == valueList.size() && jnpfField.selectType().equals("custom")) {
                    cusCheckModel.setDataList(dataList);
                    swapDataUtils.checkCustomControl(cusCheckModel, errInfo, label);
                }
                break;
            case JnpfKeyConsts.CUSTOMUSERSELECT:
                boolean cusUserErrorHapen = false;
                if (!multiple) {
                    //非多选填入多选值
                    if (valueList.size() > 1) {
                        cusUserErrorHapen = true;
                        errInfo.add(label + "非多选");
                    }
                }
                if (!cusUserErrorHapen) {
                    boolean cusUserErrorHapen1 = false;
                    boolean cusUserErrorHapen2 = false;
                    List<String> cusUserList = new ArrayList<>();
                    for (String va : valueList) {
                        String type = null;
                        String id = null;
                        if (groupMap.get(va) != null) {
                            type = "group";
                            id = groupMap.get(va).toString();
                        } else if (roleMap.get(va) != null) {
                            type = "role";
                            id = roleMap.get(va).toString();
                        } else if (depMap.get(va) != null) {
                            type = "department";
                            id = depMap.get(va).toString();
                        } else if (comMap.get(va) != null) {
                            type = "company";
                            id = comMap.get(va).toString();
                        } else if (posMap.get(va) != null) {
                            type = "position";
                            id = posMap.get(va).toString();
                        } else if (userMap.get(va) != null) {
                            type = "user";
                            id = userMap.get(va).toString();
                        }
                        if (type == null && id == null) {
                            cusUserErrorHapen1 = true;
                        } else {
                            String lastCusId = id + "--" + type;
                            if (ableIds.size() > 0) {
                                List<String> userIdList = userService.getUserIdList(ableIds);
                                if (userIdList.contains(id)) {
                                    cusUserList.add(lastCusId);
                                } else {
                                    errInfo.add(label + "值超出自定义范围");
                                }
                            } else {
                                cusUserList.add(lastCusId);
                            }
                        }
                    }
                    if (cusUserErrorHapen1) {
                        errInfo.add(label + "值不正确");
                    } else {
                        insMap.put(vModel, !multiple ? cusUserList.get(0) : JsonUtil.getObjectToString(cusUserList));
                    }
                }
                break;
            case JnpfKeyConsts.ROLESELECT:
                checkOptionsControl(multiple, insMap, vModel, label, roleMap, valueList, errInfo);
                break;
            case JnpfKeyConsts.GROUPSELECT:
                checkOptionsControl(multiple, insMap, vModel, label, groupMap, valueList, errInfo);
                break;
            case JnpfKeyConsts.ADDRESS:
                boolean addressErrorHapen = false;
                if (!multiple) {
                    //非多选填入多选值
                    if (valueList.size() > 1) {
                        addressErrorHapen = true;
                        errInfo.add(label + "非多选");
                    }
                }
                if (!addressErrorHapen) {
                    boolean addressErrorHapen1 = false;
                    valueList = Arrays.asList(value.split(","));
                    List<String[]> addresss = new ArrayList<>();
                    List<String> addressList1 = new ArrayList<>();
                    for (String va : valueList) {
                        String[] addressSplit = va.split("/");
                        if (addressSplit.length != Integer.valueOf(jnpfField.level()) + 1) {
                            addressErrorHapen1 = true;
                        }
                        List<String> addressJoined = new ArrayList<>();
                        List<String> addressParentID = new ArrayList<>();
                        for (String add : addressSplit) {
                            ProvinceEntity PRO = provinceService.getInfo(add, addressParentID);
                            if (PRO == null) {
                                addressErrorHapen1 = true;
                            } else {
                                addressJoined.add(PRO.getId());
                                addressParentID.add(PRO.getId());
                            }
                        }
                        addressList1.addAll(addressJoined);
                        addresss.add(addressJoined.toArray(new String[addressJoined.size()]));
                    }
                    if (addressErrorHapen1) {
                        errInfo.add(label + "值不正确");
                    } else {
                        insMap.put(vModel, multiple ? JsonUtil.getObjectToString(addresss) : JsonUtil.getObjectToString(addressList1));
                    }
                }
                break;
            /**
             * 系统控件
             */
            case JnpfKeyConsts.CURRORGANIZE:
                List<UserRelationEntity> OrgRelations = userRelationService.getListByUserId(userInfo.getUserId(), PermissionConst.ORGANIZE);
                insMap.put(vModel, OrgRelations.size() > 0 ? OrgRelations.get(0).getObjectId() : null);
                break;
            case JnpfKeyConsts.CURRDEPT:
                List<UserRelationEntity> depUserRelations = userRelationService.getListByUserId(userInfo.getUserId(), PermissionConst.DEPARTMENT);
                insMap.put(vModel, depUserRelations.size() > 0 ? depUserRelations.get(0).getObjectId() : null);
                break;
            case JnpfKeyConsts.CREATEUSER:
                insMap.put(vModel, userEntity.getId());
                break;
            case JnpfKeyConsts.CREATETIME:
                insMap.put(vModel, DateUtil.getNow("+8"));
                break;
            case JnpfKeyConsts.MODIFYTIME:
                //jnpfField.isUpdate() ? DateUtil.getNow("+8" ) :
                insMap.put(vModel, null);
                break;
            case JnpfKeyConsts.MODIFYUSER:
                // jnpfField.isUpdate() ? userEntity.getId() :
                insMap.put(vModel, null);
                break;
            case JnpfKeyConsts.CURRPOSITION:
                insMap.put(vModel, userEntity.getPositionId());
                break;
            case JnpfKeyConsts.BILLRULE:
                String billNo = "";
                try {
                    String rule = jnpfField.rule();
                    billNo = billRuleService.getBillNumber(rule, false);
                } catch (Exception e) {

                }
                insMap.put(vModel, billNo);
                break;
            /**
             * 基础控件
             */
            case JnpfKeyConsts.SWITCH:
                String activeTxt = jnpfField.activeTxt();
                String inactiveTxt = jnpfField.inactiveTxt();
                if (value.equals(activeTxt)) {
                    insMap.put(vModel, 1);
                } else if (value.equals(inactiveTxt)) {
                    insMap.put(vModel, 0);
                } else {
                    errInfo.add(label + "值不正确");
                }
                break;
            case JnpfKeyConsts.SLIDER:
            case JnpfKeyConsts.RATE:
                Integer Ivalue = Integer.valueOf(value);
                boolean errorHapen = false;
                if (jnpfField.min() != -1) {
                    errorHapen = Ivalue < jnpfField.min();
                }
                if (!errorHapen) {
                    if (jnpfField.max() != -1) {
                        errorHapen = Ivalue > jnpfField.max();
                    }
                }
                if (errorHapen) {
                    errInfo.add(label + "值不正确");
                }
                break;
            case JnpfKeyConsts.COM_INPUT:
                boolean comInputError = false;
                if (jnpfField.unique()) {
                    String tableName = StringUtil.isNotEmpty(jnpfField.relationTable()) ? jnpfField.relationTable() : jnpfField.tableName();
                    DbLinkEntity info = dbLinkService.getInfo(dblink);
                    DynamicDataSourceUtil.switchToDataSource(info);
                    //验证唯一
                    SqlTable sqlTable = SqlTable.of(tableName);
                    @Cleanup Connection connection = DynamicDataSourceUtil.getCurrentConnection();
                    String key = flowFormDataUtil.getKey(connection, tableName, 1);
                    String name = jnpfField.tableName().substring(0, 1).toUpperCase() + jnpfField.tableName().substring(1);
                    Class<?> aClass = Class.forName("jnpf.entity." + name + "Entity");
                    Field declaredField = aClass.getDeclaredField(jnpfField.vModel());
                    String modelValue = declaredField.getAnnotation(TableField.class).value();
                    SelectStatementProvider render = SqlBuilder.select(sqlTable.column(modelValue), sqlTable.column(key)).from(sqlTable).where(sqlTable.column(modelValue), SqlBuilder.isEqualTo(value)).build().render(RenderingStrategies.MYBATIS3);
                    List<Map<String, Object>> mapList = flowFormDataMapper.selectManyMappedRows(render);
                    int count = mapList.size();
                    if (jnpfField.isUpdate() && count > 0) {
                        comInputIDStr = String.valueOf(mapList.get(0).get(key));
                    } else {
                        if (count > 0) {
                            comInputError = true;
                            errInfo.add(label + "字段数据重复无法进行导入");
                        }
                    }
                    DynamicDataSourceUtil.clearSwitchDataSource();
                }
                //验证正则
                List<RegListModel> regList = JsonUtil.getJsonToList(jnpfField.regex(), RegListModel.class);
                if (regList != null) {
                    boolean matches;
                    for (RegListModel regListModel : regList) {
                        if (StringUtil.isNotEmpty(value)) {
                            matches = value.matches(regListModel.getPattern());
                        } else {
                            matches = false;
                        }
                        if (!matches) {
                            comInputError = true;
                            errInfo.add(label + regListModel.getMessage());
                        }
                    }
                }
                if (!comInputError) {
                    insMap.put(vModel, value);
                }
                break;
            case JnpfKeyConsts.TIME:
                try {
                    String format = jnpfField.format();
                    String today = DateUtil.dateNow("yyyy-MM-dd");
                    String thisTime = today + " " + value;
                    String formatTime = "yyyy-MM-dd " + format;
                    SimpleDateFormat formatter = new SimpleDateFormat(formatTime);
                    Date parse = formatter.parse(thisTime);
                    boolean flag = timeInRange(jnpfField, parse);
                    if (flag) {
                        insMap.put(vModel, value);
                    } else {
                        errInfo.add(label + "值不在范围内");
                    }
                } catch (Exception e) {
                    errInfo.add(label + "值不正确");
                    e.printStackTrace();
                }
                break;
            case JnpfKeyConsts.DATE:
                try {
                    String format = jnpfField.format();
                    SimpleDateFormat formatter = new SimpleDateFormat(format);
                    Date parse = formatter.parse(value);
                    boolean flag = timeInRange(jnpfField, parse);
                    if (flag) {
                        insMap.put(vModel, parse);
                    } else {
                        errInfo.add(label + "值不在范围内");
                    }
                } catch (Exception e) {
                    errInfo.add(label + "值不正确");
                    e.printStackTrace();
                }
                break;
            default:
                break;
        }
        return comInputIDStr;
    }

    /**
     * 时间是否在范围内
     *
     * @param jnpfField
     * @param parse
     * @return
     */
    private boolean timeInRange(JnpfField jnpfField, Date parse) {
        boolean flag = true;
        if (StringUtil.isNotEmpty(jnpfField.startTime())) {
            Long startTime = Long.parseLong(jnpfField.startTime());
            flag = parse.after(new Date(startTime));
        }
        if (flag && StringUtil.isNotEmpty(jnpfField.endTime())) {
            Long endTime = Long.parseLong(jnpfField.endTime());
            flag = parse.before(new Date(endTime));
        }
        return flag;
    }

    public String excelCheckForm(JnpfField jnpfField, String value, Map<String, Object> insMap, Map<String, Object> localCache, StringJoiner errorInfo) throws Exception {
        String jnpfKey = jnpfField.jnpfKey();
        String label = jnpfField.label();
        String vModel = jnpfField.vModel();
        if (value == null || "null".equals(value) || StringUtil.isEmpty(value)) {
            return null;
        }

        boolean multiple = jnpfField.multiple();
        if (JnpfKeyConsts.CHECKBOX.equals(jnpfKey)) {
            multiple = true;
        }

        boolean isCascaer = JnpfKeyConsts.CASCADER.equals(jnpfKey);
        /**
         * 数据接口
         */
        if (StringUtil.isNotEmpty(jnpfField.dataType())) {
            List<Map<String, Object>> options = new ArrayList<>();
            String dataLabel = jnpfField.dataLabel();
            String dataValue = jnpfField.dataValue();
            String children = jnpfField.dataChildren();
            String localCacheKey;
            Map<String, Object> dataInterfaceMap = new HashMap<>();
            List<String> dicSplict = Arrays.asList(value.split(","));
            if (!multiple) {
                if (dicSplict.size() > 1) {
                    errorInfo.add(label + "非多选");
                }
            }
            //静态数据
            if (jnpfField.dataType().equals(OnlineDataTypeEnum.STATIC.getType())) {
                localCacheKey = String.format("%s-%s", jnpfField.vModel(), OnlineDataTypeEnum.STATIC.getType());
                if (!localCache.containsKey(localCacheKey)) {
                    if (StringUtil.isNotEmpty(jnpfField.options())) {
                        options = JsonUtil.getJsonToListMap(jnpfField.options());
                        String Children = jnpfField.dataChildren();
                        JSONArray staticData = JsonUtil.getListToJsonArray(options);
                        getOptions(dataLabel, dataValue, Children, staticData, options);
                    } else {
                        options = JsonUtil.getJsonToListMap(jnpfField.options());
                    }
                    Map<String, Object> finalDataInterfaceMap = new HashMap<>(16);
                    String finalDataLabel = dataLabel;
                    String finalDataValue = dataValue;
                    options.stream().forEach(o -> {
                        finalDataInterfaceMap.put(String.valueOf(o.get(finalDataLabel)), o.get(finalDataValue));
                    });
                    localCache.put(localCacheKey, finalDataInterfaceMap);
                    dataInterfaceMap = finalDataInterfaceMap;
                } else {
                    dataInterfaceMap = (Map<String, Object>) localCache.get(localCacheKey);
                }
                swapDataUtils.checkFormDataInteface(multiple, insMap, vModel, label, dataInterfaceMap, dicSplict, errorInfo, isCascaer);
                //远端数据
            } else if (jnpfField.dataType().equals(OnlineDataTypeEnum.DYNAMIC.getType())) {
                localCacheKey = String.format("%s-%s-%s-%s", OnlineDataTypeEnum.DYNAMIC.getType(), jnpfField.propsUrl(), dataValue, dataLabel);
                if (!localCache.containsKey(localCacheKey)) {
                    ActionResult actionResult = dataInterfaceService.infoToId(jnpfField.propsUrl(), null, null);
                    if (actionResult != null && actionResult.getData() != null) {
                        List<Map<String, Object>> dycDataList = new ArrayList<>();
                        if (actionResult.getData() instanceof List) {
                            dycDataList = (List<Map<String, Object>>) actionResult.getData();
                        }
                        JSONArray dataAll = JsonUtil.getListToJsonArray(dycDataList);
                        String finalDataLabel2 = dataLabel;
                        String finalDataValue1 = dataValue;
                        treeToList(finalDataLabel2, finalDataValue1, children, dataAll, options);
                        Map<String, Object> finalDataInterfaceMap1 = new HashMap<>(16);

                        options.stream().forEach(o -> {
                            finalDataInterfaceMap1.put(String.valueOf(o.get(finalDataLabel2)), o.get(finalDataValue1));
                        });
                        dataInterfaceMap = finalDataInterfaceMap1;
                        localCache.put(localCacheKey, dataInterfaceMap);
                    }
                } else {
                    dataInterfaceMap = (Map<String, Object>) localCache.get(localCacheKey);
                }
                swapDataUtils.checkFormDataInteface(multiple, insMap, vModel, label, dataInterfaceMap, dicSplict, errorInfo, isCascaer);
                //数据字典
            } else if (jnpfField.dataType().equals(OnlineDataTypeEnum.DICTIONARY.getType())) {
                localCacheKey = String.format("%s-%s", OnlineDataTypeEnum.DICTIONARY.getType(), jnpfField.dictionaryType());
                dataLabel = jnpfField.dataLabel();
                dataValue = jnpfField.dataValue();
                if (!localCache.containsKey(localCacheKey)) {
                    List<DictionaryDataEntity> list = dictionaryDataService.getDicList(jnpfField.dictionaryType());
                    options = list.stream().map(dic -> {
                        Map<String, Object> dictionaryMap = new HashMap<>(16);
                        dictionaryMap.put("id", dic.getId());
                        dictionaryMap.put("enCode", dic.getEnCode());
                        dictionaryMap.put("fullName", dic.getFullName());
                        return dictionaryMap;
                    }).collect(Collectors.toList());
                    localCache.put(localCacheKey, options);
                } else {
                    options = (List<Map<String, Object>>) localCache.get(localCacheKey);
                }
                Map<String, Object> finalDataInterfaceMap1 = new HashMap<>(16);
                String finalDataLabel3 = dataLabel;
                String finalDataValue3 = dataValue;
                options.stream().forEach(o -> finalDataInterfaceMap1.put(String.valueOf(o.get(finalDataLabel3)), o.get(finalDataValue3)));
                swapDataUtils.checkFormDataInteface(multiple, insMap, vModel, label, finalDataInterfaceMap1, dicSplict, errorInfo, isCascaer);
            }
        }
        return errorInfo != null ? errorInfo.toString() : null;
    }

    private List<String> checkOptionsControl(boolean multiple, Map<String, Object> insMap, String vModel, String label, Map<String, Object> cacheMap, List<String> valueList, StringJoiner errInfo) {
        boolean error = false;
        if (!multiple) {
            //非多选填入多选值
            if (valueList.size() > 1) {
                error = true;
                errInfo.add(label + "非多选");
            }
        }
        List<String> dataList = new ArrayList<>();
        if (!error) {
            boolean errorHapen = false;
            for (String va : valueList) {
                Object vo = cacheMap.get(va);
                if (vo == null) {
                    errorHapen = true;
                } else {
                    dataList.add(vo.toString());
                }

            }
            if (errorHapen) {
                errInfo.add(label + "值不正确");
            } else {
                insMap.put(vModel, !multiple ? dataList.get(0) : JsonUtil.getObjectToString(dataList));
            }
        }
        return dataList;
    }

    /**
     * 递归查询
     *
     * @param label
     * @param value
     * @param Children
     * @param data
     * @param options
     */
    public static void getOptions(String label, String value, String Children, JSONArray data, List<Map<String, Object>> options) {
        for (int i = 0; i < data.size(); i++) {
            JSONObject ob = data.getJSONObject(i);
            Map<String, Object> tree = new HashMap<>(16);
            tree.put(value, String.valueOf(ob.get(value)));
            tree.put(label, String.valueOf(ob.get(label)));
            options.add(tree);
            if (ob.get(Children) != null) {
                JSONArray childrenArray = ob.getJSONArray(Children);
                getOptions(label, value, Children, childrenArray, options);
            }
        }
    }

    /**
     * 获取用户主件查询条件
     *
     * @param value
     * @return
     */
    public List<String> usersSelectQuery(String value) {
        List<String> userSList = new ArrayList<>();
        String userValue = value.substring(0, value.indexOf("--"));
        UserEntity userEntity = userService.getInfo(userValue);
        if (userEntity != null) {
            //在用户关系表中取出
            List<UserRelationEntity> groupRel = Optional.ofNullable(userRelationService.getListByObjectType(userValue, PermissionConst.GROUP)).orElse(new ArrayList<>());
            List<UserRelationEntity> posRel = Optional.ofNullable(userRelationService.getListByObjectType(userValue, PermissionConst.POSITION)).orElse(new ArrayList<>());
            List<UserRelationEntity> roleRel = Optional.ofNullable(userRelationService.getListByObjectType(userValue, PermissionConst.ROLE)).orElse(new ArrayList<>());

            if (groupRel.size() > 0) {
                for (UserRelationEntity split : groupRel) {
                    userSList.add(split.getObjectId());
                }
            }
            if (StringUtil.isNotEmpty(userEntity.getOrganizeId())) {
                //向上递归 查出所有上级组织
                List<String> allUpOrgIDs = new ArrayList<>();
                organizeService.upWardRecursion(allUpOrgIDs, userEntity.getOrganizeId());
                for (String orgID : allUpOrgIDs) {
                    userSList.add(orgID);
                }
            }
            if (posRel.size() > 0) {
                for (UserRelationEntity split : posRel) {
                    userSList.add(split.getObjectId());
                }
            }
            if (roleRel.size() > 0) {
                for (UserRelationEntity split : roleRel) {
                    userSList.add(split.getObjectId());
                }
            }
            return userSList;
        } else {
            return null;
        }
    }

    /**
     * 获取用户主件查询条件(多选)
     *
     * @param values
     * @return
     */
    public List<String> usersSelectQuery(List<String> values) {
        List<String> userSList = new ArrayList<>();
        for (String value : values) {
            String userValue = value.substring(0, value.indexOf("--"));
            UserEntity userEntity = userService.getInfo(userValue);
            if (userEntity != null) {
                //在用户关系表中取出
                List<UserRelationEntity> groupRel = Optional.ofNullable(userRelationService.getListByObjectType(userValue, PermissionConst.GROUP)).orElse(new ArrayList<>());
                List<UserRelationEntity> posRel = Optional.ofNullable(userRelationService.getListByObjectType(userValue, PermissionConst.POSITION)).orElse(new ArrayList<>());
                List<UserRelationEntity> roleRel = Optional.ofNullable(userRelationService.getListByObjectType(userValue, PermissionConst.ROLE)).orElse(new ArrayList<>());

                if (groupRel.size() > 0) {
                    for (UserRelationEntity split : groupRel) {
                        userSList.add(split.getObjectId());
                    }
                }
                if (StringUtil.isNotEmpty(userEntity.getOrganizeId())) {
                    //向上递归 查出所有上级组织
                    List<String> allUpOrgIDs = new ArrayList<>();
                    organizeService.upWardRecursion(allUpOrgIDs, userEntity.getOrganizeId());
                    for (String orgID : allUpOrgIDs) {
                        userSList.add(orgID);
                    }
                }
                if (posRel.size() > 0) {
                    for (UserRelationEntity split : posRel) {
                        userSList.add(split.getObjectId());
                    }
                }
                if (roleRel.size() > 0) {
                    for (UserRelationEntity split : roleRel) {
                        userSList.add(split.getObjectId());
                    }
                }
            }
        }
        return userSList;
    }
    @DS("")
    public List<RuleInfo> getFilterCondition(String id) {
        return filterService.getCondition(id);
    }

    public static List convertToList(Object obj) {
        return OnlineSwapDataUtils.convertToList(obj);
    }

    public static String convertValueToString(String obj, boolean mult, boolean isOrg) {
        return OnlineSwapDataUtils.convertValueToString(obj, mult, isOrg);
    }

    /**
     * 获取数据连接
     *
     * @param dbLink
     * @return
     */
    public DbLinkEntity getDataSource(String dbLink) {
        QueryWrapper<DbLinkEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(DbLinkEntity::getFullName, dbLink);
        return dblinkService.getOne(queryWrapper);
    }


    /**
     * 静态数据转换
     *
     * @param param    需要转换的值
     * @param options  静态数据模型
     * @param key      label key-value编码对应
     * @param multiple 是否多选
     * @return 转换后的值
     */
    public static String selectStaitcSwap(String param, String options, String key, String label, boolean multiple) {
        List<String> textList = new ArrayList<>();
        List<Map> optionsList = JsonUtil.getJsonToList(options, Map.class);
        if (multiple) {
            List<String> jsonToList = JsonUtil.getJsonToList(param, String.class);
            for (String list1 : jsonToList) {
                if (list1.contains("[")) {
                    List<String> textList2 = new ArrayList<>();
                    List<String> jsonToList2 = JsonUtil.getJsonToList(list1, String.class);
                    for (String str : jsonToList2) {
                        textList2.add(loop(optionsList, str, key, label));
                    }
                    textList.add(String.join("/", textList2));
                } else {
                    textList.add(loop(optionsList, list1, key, label));
                }
            }
        } else {
            if (param.contains("[")) {
                List<String> textList2 = new ArrayList<>();
                List<String> jsonToList = JsonUtil.getJsonToList(param, String.class);
                for (String str : jsonToList) {
                    textList2.add(loop(optionsList, str, key, label));
                }
                textList.add(String.join("/", textList2));
            } else {
                textList.add(loop(optionsList, param, key, label));
            }
        }
        return String.join(",", textList);
    }

    public static String loop(List<Map> options, String oneData, String key, String label) {
        for (int i = 0; i < options.size(); i++) {
            if (options.get(i).get(key).equals(oneData)) {
                return options.get(i).get(label).toString();
            } else if (options.get(i).get("children") != null) {
                List<Map> children = JsonUtil.getJsonToList(options.get(i).get("children"), Map.class);
                String loop = loop(children, oneData, key, label);
                if (loop != null) {
                    return loop;
                }
            }
        }
        return null;
    }

    /**
     * 功能表单获取流程信息-导入绑定多流程的第一个
     *
     * @param formId
     * @return
     * @throws WorkFlowException
     */
    public String getFlowTempJsonId(String formId) throws WorkFlowException {
        String flowTemjsonId = "";
        FlowFormEntity form = flowFormService.getById(formId);
        if (form == null || StringUtil.isEmpty(form.getFlowId())) {
            throw new WorkFlowException("该功能未配置流程不可用");
        }
        FlowTemplateInfoVO vo = flowTemplateService.info(form.getFlowId());
        if (vo == null || StringUtil.isEmpty(vo.getFlowTemplateJson()) || "[]".equals(vo.getFlowTemplateJson())) {
            throw new WorkFlowException("流程未设计！");
        }
        List<FlowJsonModel> collect = JsonUtil.getJsonToList(vo.getFlowTemplateJson(), FlowJsonModel.class);
        flowTemjsonId = collect.get(0).getId();
        return flowTemjsonId;
    }


    /**
     *  输入时表单时间字段根据格式转换去尾巴
     * @param form
     */
    public static void swapDatetime(Object form) {
        Field[] declaredFields = form.getClass().getDeclaredFields();
        for (Field f : declaredFields) {
            try {
                //副表处理
                if (f.getType().getName().startsWith("jnpf.model")) {
                    if (!f.isAccessible()) {
                        f.setAccessible(true);
                    }
                    Object o = f.get(form);
                    if (o == null) {
                        continue;
                    }
                    swapDatetime(o);
                    f.set(form, o);
                    continue;
                }
                //子表处理
                if (List.class.isAssignableFrom(f.getType())) {
                    Type type = f.getGenericType();
                    if (type instanceof ParameterizedType) {
                        if (!f.isAccessible()) {
                            f.setAccessible(true);
                        }
                        List list = getList(f, f.get(form));
                        for(Object o:list){
                            swapDatetime(o);
                        }
                        if(list.size()>0){
                            f.set(form, list);
                        }
                    }
                    continue;
                }
                //主表处理
                if (f.getAnnotation(JnpfField.class) == null) continue;
                JnpfField annotation = f.getAnnotation(JnpfField.class);
                if (!"date".equals(annotation.jnpfKey()) || StringUtil.isEmpty(annotation.format())) continue;
                String format = annotation.format();
                f.setAccessible(true);
                if (f.get(form) != null && Long.parseLong(String.valueOf(f.get(form))) > 0) {
                    Date date = new Date(Long.parseLong(String.valueOf(f.get(form))));
                    String completionStr = "";
                    switch (format) {
                        case "yyyy":
                            completionStr = "-01-01 00:00:00";
                            break;
                        case "yyyy-MM":
                            completionStr = "-01 00:00:00";
                            break;
                        case "yyyy-MM-dd":
                            completionStr = " 00:00:00";
                            break;
                        case "yyyy-MM-dd HH":
                            completionStr = ":00:00";
                            break;
                        case "yyyy-MM-dd HH:mm":
                            completionStr = ":00";
                            break;
                        default:
                            break;
                    }
                    String datestr = DateUtil.dateToString(date, format);
                    long time = DateUtil.stringToDate(datestr + completionStr).getTime();
                    f.set(form, String.valueOf(time));
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

    public static List getList(Field field, Object object) {
        List resultList = new ArrayList<>();
        if (object != null) {
            try {
                Class clzz = object.getClass();
                //反射调用获取到list的size方法来获取到集合的大小
                Method sizeMethod = clzz.getDeclaredMethod("size");
                if (!sizeMethod.isAccessible()) {
                    sizeMethod.setAccessible(true);
                }
                //集合长度
                int size = (int) sizeMethod.invoke(object);
                //循环遍历获取到数据
                for (int i = 0; i < size; i++) {
                    //反射获取到list的get方法
                    Method getMethod = clzz.getDeclaredMethod("get", int.class);
                    //调用get方法获取数据
                    if (!getMethod.isAccessible()) {
                        getMethod.setAccessible(true);
                    }
                    Object invoke = getMethod.invoke(object, i);
                    resultList.add(invoke);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return resultList;

    }

    /**
     *  小数转换带上0
     * @param decimalValue
     */
    public static String getDecimalStr(Object decimalValue){
        if (decimalValue instanceof BigDecimal) {
            BigDecimal bd = (BigDecimal) decimalValue;
            return bd.toPlainString();
        }
        return String.valueOf(decimalValue);
    }


}
